package com.zhongshengnetwork.rightbe.commentstore.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.ItemTouchHelper;

import android.Manifest;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.huantansheng.easyphotos.EasyPhotos;
import com.huantansheng.easyphotos.models.album.entity.Photo;
import com.hys.utils.ImageUtils;
import com.hys.utils.InitCacheFileUtils;
import com.yalantis.ucrop.UCrop;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.commentstore.model.CommentStoreClassifyModel;
import com.zhongshengnetwork.rightbe.commentstore.model.CommentStoreModel;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.PermissionUtils;
import com.zhongshengnetwork.rightbe.common.QiniuCallBack;
import com.zhongshengnetwork.rightbe.common.QiniuUploadModel;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.customview.ActionSheetDialog;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.QiniuModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.imageviewer.ViewData;
import com.zhongshengnetwork.rightbe.imageviewer.widget.ImageViewer;
import com.zhongshengnetwork.rightbe.lang.model.BookmarkModel;
import com.zhongshengnetwork.rightbe.lang.view.PostArticleImgAdapter;
import com.zhongshengnetwork.rightbe.login.BDThirdActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;
import com.zhongshengnetwork.rightbe.wzt.view.GlideEngine;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class NewCommentStoreActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    public static final String FILE_DIR_NAME = "com.zhongshengnetwork.rightbe";//应用缓存地址
    public static final String FILE_IMG_NAME = "images";//放置图片缓存
    private static final int REQUEST_PUBLISH = 1002;
    private static final int LANG_TYPE = 1119;
    private static final int REQUEST_LOCATION = 1211;//地理位置
    private static final int TAKE_PICTURE = 1212;//拍照
    private static final int CHOOSE_PICTURE = 1214;//从相册选择
    private static final int REQUEST_LABEL = 1213; //选择标签
    private static final int CROP_PICTURE = 1003;//裁剪图片
    private static final int SELECT_COMMENT_STORE = 1215; //选择评论库
    private static final int REQUEST_PERMISSION = 10003;

    private TopBarView topbar;

    private Context mContext;
    private PostArticleImgAdapter postArticleImgAdapter;
    private ItemTouchHelper itemTouchHelper;
    private EditText et_content;

    private int imgIndex = 0;
    private QiniuModel qiniuModel = null;
    private boolean isUploading = false;
    private Timer mTimer = null;
    private TimerTask mTimerTask = null;
    private static int delay = 100;
    private static int period = 1000;  //1s
    private boolean timerFlag = false;

    private boolean isRepublish = false;
    private boolean isNewBitmap = false;

    private RelativeLayout publish_menu_visible;
    private TextView publish_menu_visible_text;

    private List<String> nameList = null;
    private List<String> itemList = null;
    private boolean isPublishing = false;//发布状态，控制重复发布
    private CommentStoreModel classifyModel;

    private KyLoadingBuilder loadingBuilder;

    //绑定手机号
    private boolean bindMobile(){
        if (CommonUtils.isLogin() == true){
            if (!CommonUtils.isEmpty(CustomApplication.loginModel.getNeed()) && CustomApplication.loginModel.getNeed().equals("1")){
                if (CommonUtils.isEmpty(CustomApplication.loginModel.getMobile())){
                    Intent intent = new Intent(NewCommentStoreActivity.this, BDThirdActivity.class);
                    startActivity(intent);
                    return true;
                }
            }
        }
        return false;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_new_comment_store);

        classifyModel =  (CommentStoreModel) getIntent().getSerializableExtra("model");
        if (classifyModel == null){
            isRepublish = false;
            classifyModel = new CommentStoreModel();
            classifyModel.setClassifyId(getIntent().getIntExtra("classifyId", 0));
            classifyModel.setClassifyName(CommonUtils.formatString(getIntent().getStringExtra("classifyName")));
        }else {
            isRepublish = true;
        }
        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        if (isRepublish == true){
            topbar.getTitleView().setText("编辑评论");
        }
        topbar.getRightTextView().setText("发布");
        topbar.getRightTextView().setTextSize(15);
        topbar.getRightTextView().setClickable(true);
        topbar.getRightTextView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                if (CommonUtils.isLogin() == false){
                    Intent intent = new Intent(NewCommentStoreActivity.this, LoginActivity.class);
                    startActivity(intent);
                    return;
                }
                publishLang();
            }
        });


        publish_menu_visible = (RelativeLayout) findViewById(R.id.publish_menu_visible);
        publish_menu_visible.setClickable(true);
        publish_menu_visible.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hintKeyBoard();
                onClickVisible();
            }
        });
        publish_menu_visible_text = (TextView) findViewById(R.id.publish_menu_visible_text);

        initView();

        RelativeLayout new_classify_layout = (RelativeLayout) findViewById(R.id.new_classify_layout);
        new_classify_layout.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

        LinearLayout et_title_line = (LinearLayout) findViewById(R.id.et_title_line);
        et_title_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());

        LinearLayout publish_menu_original_line = (LinearLayout) findViewById(R.id.publish_menu_original_line);
        publish_menu_original_line.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        LinearLayout line1 = (LinearLayout) findViewById(R.id.line1);
        line1.setBackgroundColor(AppThemeUtils.getInstance().getBackgroundColor());
        et_content.setHintTextColor(AppThemeUtils.getInstance().getLightTextColor());
        et_content.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        TextView publish_menu_visible_title = (TextView) findViewById(R.id.publish_menu_visible_title);
        publish_menu_visible_title.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
        publish_menu_visible_text.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

        initData();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LoginActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        back();
    }

    @Override
    public void onBackPressed()
    {
        Log.e("TAG","按下返回键了");
        back();
    }

    private void back(){
        hintKeyBoard();
        final CustomDialog.Builder builder = new CustomDialog.Builder(NewCommentStoreActivity.this);
        builder.setTitle("温馨提示");
        builder.setMessage("是否要放弃本次发布？");
        builder.setPositiveButton("放弃", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        CustomDialog dialog = builder.create();
        dialog.show();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

    private void onClickVisible(){
        Intent intent = new Intent(NewCommentStoreActivity.this, CommentStoreClassifyActivity.class);
        intent.putExtra("isSelect", true);
        startActivityForResult(intent, SELECT_COMMENT_STORE);
    }

    private void initData() {

        if (isRepublish == true){
            et_content.setText(CommonUtils.formatString(classifyModel.getContent()));
        }
        if (!CommonUtils.isEmpty(classifyModel.getClassifyName())){
            publish_menu_visible_text.setText(classifyModel.getClassifyName());
        }
        mContext = getApplicationContext();
        if (PermissionUtils.hasSDCard() == true){
            InitCacheFileUtils.initImgDir(FILE_DIR_NAME, FILE_IMG_NAME);//清除图片缓存
        }

    }

    private void initView() {
        et_content = (EditText) findViewById(R.id.et_content);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri imageUri = null;
        if (requestCode == SELECT_COMMENT_STORE && resultCode == RESULT_OK) {//从相册选择完图片
            if (data != null){
                CommentStoreClassifyModel m =  (CommentStoreClassifyModel) data.getSerializableExtra("model");
                if (m != null){
                    classifyModel.setClassifyId(m.getClassifyId());
                    classifyModel.setClassifyName(m.getClassifyName());
                    publish_menu_visible_text.setText(classifyModel.getClassifyName());
                }
            }
        }
    }

    //以下是发布流程
    private void publishLang(){

        if (bindMobile() == true){
            return;
        }

//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
//                && ContextCompat.checkSelfPermission(NewCommentStoreActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(NewCommentStoreActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE},
//                    REQUEST_PERMISSION);
//            ToastUtil.show(NewCommentStoreActivity.this,"亲，请开启应用对SD卡的读写权限");
//            return;
//        }

        if (isPublishing == true){
            ToastUtil.show(NewCommentStoreActivity.this, "发布中，请稍后...");
            return;
        }

        if (et_content.getText().length() == 0){
            classifyModel.setContent("");
        }else {
            classifyModel.setContent(et_content.getText().toString());
        }

        if (CommonUtils.isEmpty(classifyModel.getContent())){
            ToastUtil.show(NewCommentStoreActivity.this, "亲，请输入评论内容哦~");
            return;
        }
        isPublishing = true;
        loadingBuilder = new KyLoadingBuilder(NewCommentStoreActivity.this);
        loadingBuilder.setIcon(R.drawable.loading04);
        loadingBuilder.setText("发布中...");
        loadingBuilder.setOutsideTouchable(false);//点击空白区域是否关闭
        loadingBuilder.setBackTouchable(true);//按返回键是否关闭
        loadingBuilder.show();
        uploadLang();
    }

    //上传内容
    private void uploadLang(){
        final HashMap<String, String> map = new HashMap<String, String>();
        String url = "comment/store/content/add.do";
        if (isRepublish == true){
            url = "comment/store/content/edit.do";
            map.put("commentId", classifyModel.getCommentId()+"");
        }

        map.put("token", CommonUtils.formatString(CustomApplication.loginModel.getToken()));
        map.put("title",classifyModel.getContent());
        map.put("classifyId", classifyModel.getClassifyId()+"");
        Log.e("TAG","发布参数："+map.toString());
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(final String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            loadingBuilder.dismiss();
                            ToastUtil.show(NewCommentStoreActivity.this, "发布成功");
                            setResult(RESULT_OK);
                            finish();
                        }else {
                            loadingBuilder.dismiss();
                            isPublishing = false;
                            CustomApplication.showTip(commonModel, NewCommentStoreActivity.this);
                        }
                    }
                });
            }

            @Override
            public void onError(String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        loadingBuilder.dismiss();
                        isPublishing = false;
                        ToastUtil.show(NewCommentStoreActivity.this,"发布失败，请稍后重试");
                    }
                });
            }
        });

    }

}
